package li.brauch.semesterarbeit.radio.sound;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;

public class MP3Player {
	
	private List<MP3PlayerListener> mp3PlayerListener = new ArrayList<MP3PlayerListener>();
	
	private Thread playerThread;
	private Thread durationThread;
	private Player player;
	private InputStream is;
	
	public MP3Player() {}
	
	public void stop() {
		if (playerThread != null && playerThread.isAlive()) {
			try {
				player.stop();
				playerThread.join();
				player = null;
				playerThread = null;
				durationThread.join();
				durationThread = null;
			} catch (InterruptedException e) {}
		}
	}
	
	public void pause(boolean paused) {
		synchronized(player) {
			if (paused)
				player.pause();
			else
				player.resume();
		}
	}
	
	public void play(URL url) throws MP3PlayerException {
		try {
			// for local mp3
			is = url.openStream();
			
			// for http streaming mp3
			//is = AudioSystem.getAudioInputStream(url);
			
			player = new Player(is);

			// play mp3 without blocking
			playerThread = new Thread(new Runnable() {
				public void run() {
					
					try {
						
						// more frames available to play?
						boolean skiped = player.play(Integer.MAX_VALUE);
						
						try {
							is.close();
						} catch (IOException e) {
						}
						
						player = null;
						playerThread = null;
						
						// notify only when mp3 is played to the end
						if (!skiped) {
							notifyPlaybackFinished();	
						}
						
					} catch (JavaLayerException e) {}
				}
			});
			playerThread.start();
			
			durationThread = new Thread(new Runnable() {
				
				private long position = 0;
				
				public void run() {
					while (player != null) {
						notifyPositionUpdated(position);
						position += 1000;
						try {
							Thread.sleep(1000);
						} catch (InterruptedException e) {}
					}
				}
			});
			durationThread.start();
		} catch (FileNotFoundException e) {
			throw new MP3PlayerException(e.getMessage() + " was not found");
		} catch (java.io.IOException e) {
			throw new MP3PlayerException("I/O-Error during reading mp3-Song");			
		} catch (JavaLayerException e) {
			
			throw new MP3PlayerException(e.getMessage());
		/*} catch (UnsupportedAudioFileException e) {
			throw new MP3PlayerException("error reading mp3-file");*/
		}
	}
	
	public void addMP3PlayerListener(MP3PlayerListener listener) {
		mp3PlayerListener.add(listener);
	}
	
	protected void notifyPlaybackFinished() {
		for (MP3PlayerListener listener : mp3PlayerListener) {	
			listener.playbackFinished();
		}
	}
	
	protected void notifyPositionUpdated(long position) {
		for (MP3PlayerListener listener : mp3PlayerListener) {
			listener.positionUpdated(position);
		}
	}
}
